package org.deng.learn.designpattern.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @ Author: DengLibin
 * @ Description:
 * @ DateTime:  16:01 2018/5/6 0006
 */
public class TeacherProxy implements MethodInterceptor {
    private Teacher teacher  = new Teacher();//维护一个目标对象
    //给目标对象创建代理对象


    public Teacher getTeacheProxyInstance() {
        //1、工具类类
        Enhancer en = new Enhancer();
        //2、设置父类
        en.setSuperclass(teacher.getClass());
        //3、设置回调方法
        en.setCallback(this);
        return (Teacher) en.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        if(method.getName().equals("teach")){
            System.out.println("代理教师授课");
            return method.invoke(teacher,args);
        }
        return null;
    }
}
